package com.twetec.cms.adapter.pc.backend.tag;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.twetec.cms.adapter.pc.backend.tag.annotation.TplTag;
import com.twetec.cms.adapter.pc.backend.tag.doc.TagDocObject;
import com.twetec.cms.common.constant.ColumnEnum;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.website.ColumnPO;
import com.twetec.cms.model.po.website.SiteColumnPO;
import com.twetec.cms.model.po.website.SitePO;
import com.twetec.cms.service.website.ColumnService;
import com.twetec.cms.service.website.SiteColumnService;
import com.twetec.cms.service.website.SiteService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.tag.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service()
@Scope("prototype")
@TplTag("navList")
public class NavListTag extends GeneralVarTagBinding {

	@Autowired
	private SiteService siteService;

	@Autowired
	private ColumnService columnService;

	@Autowired
	private SiteColumnService siteColumnService;

	@Override
	public void render() {
		System.out.println("NavListTag");

		// 接收标签参数
		Map result = Maps.newHashMap();
		// 站点id
		Long siteId=  (this.getAttributeValue("siteId") instanceof String) ?
				Long.parseLong((String) this.getAttributeValue("siteId")) : (Long) this.getAttributeValue("siteId");
		// 栏目id
		Long parentColumnId=  (this.getAttributeValue("parentColumnId") instanceof String) ?
				Long.parseLong((String) this.getAttributeValue("parentColumnId")) : (Long) this.getAttributeValue("parentColumnId");

		// 获取站点信息
		SitePO sitePO = siteService.getById(siteId);

		if (!ValidateUtil.isNullOrEmpty(sitePO)) {

			List<ColumnPO> columnPOList = new ArrayList<>();
			// 如果传入的parentColumnId是0，就获取站点对应的顶级栏目信息
			if (new Long("0").equals(parentColumnId)) {
				QueryWrapper<SiteColumnPO> siteColumnPOQueryWrapper = new QueryWrapper<>();
				siteColumnPOQueryWrapper.eq("SITE_ID", siteId);
				List<SiteColumnPO> list = siteColumnService.list(siteColumnPOQueryWrapper);
				ArrayList<Long> columnIdList = new ArrayList<>();
				if (!ValidateUtil.isNullOrEmpty(list)) {
					for (SiteColumnPO siteColumnPO : list) {
						columnIdList.add(siteColumnPO.getColumnId());
					}
				}
				QueryWrapper<ColumnPO> columnPOQueryWrapper = new QueryWrapper<ColumnPO>();
				columnPOQueryWrapper.in("ID", columnIdList);
				columnPOQueryWrapper.eq("IS_RECOVERY", 0);
				columnPOQueryWrapper.eq("IS_NAV", 1);
				columnPOQueryWrapper.orderByDesc("SORT");
				columnPOQueryWrapper.orderByAsc("ID");
				columnPOList = columnService.list(columnPOQueryWrapper);
			} else {
				// 如果传入的parentColumnId不是0，就获取该栏目下的子栏目信息
				QueryWrapper<ColumnPO> childColumnQueryWrapper = new QueryWrapper<>();
				childColumnQueryWrapper.eq("PARENT_ID", parentColumnId);
				childColumnQueryWrapper.eq("IS_NAV", 1);
				childColumnQueryWrapper.eq("IS_RECOVERY", 0);
				childColumnQueryWrapper.orderByDesc("SORT");
				childColumnQueryWrapper.orderByAsc("ID");
				columnPOList = columnService.list(childColumnQueryWrapper);
			}

			// 如果查询到的栏目集合不为空
			if (!ValidateUtil.isNullOrEmpty(columnPOList)) {

				// 遍历展示的栏目集合
				for (int i = 0; i < columnPOList.size(); i ++) {
//					String url = sitePO.getDomainUrl();
					String url = "";

					// 如果是首页
					if (columnPOList.get(i).getType().equals(ColumnEnum.SITE_INDEX.getType())) {
//						url = sitePO.getDomainUrl() + File.separator + "index.html";
						url = "/index.html";
					} else {
						// 如果不是首页,就跳转到栏目列表页。或者文章列表页
						ColumnPO childColumnPO = new ColumnPO();
						QueryWrapper<ColumnPO> childColumnQueryWrapper = new QueryWrapper<>();
						childColumnQueryWrapper.eq("PARENT_ID", columnPOList.get(i).getId());
						childColumnQueryWrapper.eq("IS_RECOVERY", 0);
						childColumnQueryWrapper.last(" and rownum = 1");
						childColumnPO = columnService.getOne(childColumnQueryWrapper);
						// 如果有子栏目
						if (null != childColumnPO) {
							url =  childColumnPO.getEncodedXpath() + File.separator + "index.html";
						} else {
							// 如果没有子栏目
							url =  columnPOList.get(i).getEncodedXpath() + File.separator + "index.html";
						}
					}

					String name = columnPOList.get(i).getName();
					String columnCode = columnPOList.get(i).getEncoded();
					String type = columnPOList.get(i).getType();
					// 返回标签参数
					result.put("name", name);
					result.put("encoded", columnCode);
					result.put("type", type);
					result.put("url", url.replace("\\", "/"));

					this.binds(result);
					this.doBodyRender();
				}
			}

		}

	}


	/**
	 * 标签文档
	 * @return
	 */
	public static TagDocObject doc() {
		TagDocObject tagDocObject = new TagDocObject();
		tagDocObject.setTagName("navList");
		tagDocObject.setDesc("导航标签");
		tagDocObject.setExample("<#navList serverUrl=\"${serverUrl}\" siteId=\"${site.siteId!}\" parentColumnId=\"0\" pageType=\"${pageType}\" var=\"data\">" +
				"        	<li>\n" +
				"      			<a href=\"${data.url!}\" target=\"_blank\">${data.name!}</a>\n" +
				"    		</li>\n" +
				"      </#navList>");

		tagDocObject.setParamDesc("siteId：所属站点id\n" +
				"parentColumnId：父栏目id默认为0\n" +
				"serverUrl：资讯发布系统的域名或IP和Port\n" +
				"dm：站点域名\n" +
				"pageType：用于标识是生成静态页面还是预览（预览：checkPage，生成：null或staticPage）\n" +
				"--------- var: 标签的数据结果集 ---------\n" +
				"name：栏目名称\n" +
				"encoded：栏目编码\n" +
				"type：栏目类型\n" +
				"url：跳转地址");

		tagDocObject.setOtherDesc("无");

		return tagDocObject;
	}

}
